package handler

import (
	"github.com/gin-gonic/gin"
	"im/api/request"
	"im/internal/dao"
	"im/internal/model"
)

func ApplyUser(c *gin.Context) {
	var req request.ApplyUserReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Id: req.UserId}, &user)
	if user.Id == 0 {
		c.JSON(200, gin.H{
			"code": 10001,
			"msg":  "用户未登录",
			"data": nil,
		})
		return
	}
	mate := model.Mate{
		UserId:     req.UserId,
		MateId:     req.MateId,
		MateStatus: req.MateStatus,
	}
	if !dao.Create(&mate) {
		c.JSON(200, gin.H{
			"code": 10002,
			"msg":  "好友申请发送失败",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "好友申请发送成功",
		"data": nil,
	})
}

func UpdateMate(c *gin.Context) {
	var req request.UpdateMateReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Id: req.MateId}, &user)
	if user.Id == 0 {
		c.JSON(200, gin.H{
			"code": 10001,
			"msg":  "用户未登录",
			"data": nil,
		})
		return
	}
	mate := model.Mate{
		Id:         req.Id,
		MateId:     req.MateId,
		MateStatus: req.MateStatus,
	}
	if !dao.Update(&mate) {
		c.JSON(200, gin.H{
			"code": 10002,
			"msg":  "好友申请验证失败",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "好友申请验证成功",
		"data": nil,
	})
}

func DeleteMate(c *gin.Context) {
	var req request.UpdateMateReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Id: req.MateId}, &user)
	if user.Id == 0 {
		c.JSON(200, gin.H{
			"code": 10001,
			"msg":  "用户未登录",
			"data": nil,
		})
		return
	}
	mate := model.Mate{
		Id:         req.Id,
		MateId:     req.MateId,
		MateStatus: req.MateStatus,
	}
	if !dao.Update(&mate) {
		c.JSON(200, gin.H{
			"code": 10002,
			"msg":  "好友删除失败",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "好友删除成功",
		"data": nil,
	})
}
